package LeetCode.leetcode637;


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        Double itemRes = 0.0d;
        List<Double> res = new ArrayList<>();
        TreeNode tmp;
        int count = 0;
        queue.offer(root);
        int length;
        while (!queue.isEmpty()){
            length = queue.size();
            while (length > 0){
                tmp = queue.poll();
                itemRes+=tmp.val;
                count++;
                if (tmp.left != null)
                    queue.offer(tmp.left);
                if (tmp.right != null)
                    queue.offer(tmp.right);
                length--;
            }
            //添加结果
            res.add(itemRes / count);
            //置零
            itemRes = 0d;
            count = 0;
        }

        return res;
    }
}
